package com.property.manage.service.parking;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guardchina.framework.util.exception.BusinessException;
import com.property.manage.dao.flowingWater.FlowingWaterExpandMapper;
import com.property.manage.dao.flowingWater.FlowingWaterMapper;
import com.property.manage.dao.parking.ParkingRentPayRecordMapper;
import com.property.manage.enums.WalletType;
import com.property.manage.model.flowingWater.FlowingWaterEntity;
import com.property.manage.model.flowingWater.FlowingWaterExpandEntity;
import com.property.manage.model.parking.ParkingRentPayRecordEntity;
import com.property.manage.model.system.SysSet;
import com.property.manage.model.system.User;
import com.property.manage.service.flowingWater.FlowingWaterService;
import com.property.manage.service.flowingWater.WalletService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Optional;

/**
 * 描述
 *
 * @author lwb
 * @since 2020/9/14
 */
@Component
@Slf4j
public class ParkingRentPayRecordService {

    private ParkingRentPayRecordMapper parkingRentPayRecordMapper;

    @Autowired
    private WalletService walletService;


    @Autowired
    private FlowingWaterService flowingWaterService;

    @Autowired
    private FlowingWaterMapper flowingWaterMapper;

    @Autowired
    private FlowingWaterExpandMapper flowingWaterExpandMapper;

    @Transactional(rollbackFor = Exception.class)
    public Integer pay(User payee, Integer buildingId, Integer rentId, BigDecimal money, BigDecimal cash, BigDecimal advance, BigDecimal advanceReturn, String payType, String remark, String billNo, Byte type, BigDecimal shouldPay, Byte otherType) {

        log.info("车位出租缴费：userName[{}], buildingId[{}], rentId[{}], money[{}], cash[{}], advance[{}], advanceReturn[{}], payType[{}], remark[{}], billNo[{}]", payee.getUserName(), buildingId, remark, money, cash, advance, advanceReturn, payType, remark, billNo);

        if (cash.add(advance).subtract(advanceReturn).compareTo(money) != 0) {
            throw new BusinessException("缴费金额不一致", "cash.add(advance).subtract(advanceReturn).compareTo(money)");
        }


        if (advance.compareTo(BigDecimal.ZERO) > 0) {
            walletService.updateExpenditure(buildingId, advance, WalletType.PARKING);
        }

        if (advanceReturn.compareTo(BigDecimal.ZERO) < 0) {
            walletService.changeDeposit(buildingId, advanceReturn, WalletType.PARKING);
        }

        BigDecimal balance = walletService.findBalance(buildingId, WalletType.PARKING);

        ParkingRentPayRecordEntity payRecord = new ParkingRentPayRecordEntity();
        payRecord.setRentId(rentId);
        payRecord.setMoney(money);
        payRecord.setCash(cash);
        payRecord.setAdvance(advance);
        payRecord.setAdvanceReturn(advanceReturn);
        payRecord.setAdvanceRemain(balance);
        payRecord.setPayee(payee.getUserName());
        payRecord.setPayType(payType);
        payRecord.setRemark(remark);
        payRecord.setBillNo(billNo);
        payRecord.setPayTime(LocalDateTime.now());
        payRecord.setType(type);
        payRecord.setState(ParkingRentPayRecordEntity.STATE_NORMAL);

        parkingRentPayRecordMapper.insert(payRecord);

        //创建流水
        //user 用户信息，buildingId 楼栋ID，shouldPay 应收金额，realFee 实付金额，subtractFee 差额，preStorage 使用预存金额，
        // expenditure 当前预存，cash 现金，small 转存的零钱存入流水，listOfCharges 收费名目， type 收费类型， explain 说明， remarks 备注，
        // payType 付款方式 1现金 2微信 3支付宝 4统一划扣 ， billNo  票据编号， otherType 状态 0-正常收费 1-欠费收取

        FlowingWaterExpandEntity flowingWaterEntity = flowingWaterService.createFlowingWaterEntityByBuildingId(payee, buildingId,
                shouldPay, money, BigDecimal.ZERO, advance, balance, cash, advanceReturn,
                "车位租金划扣", 1, remark, otherType == 0 ? "批量划扣" : "欠取收费",
                payType, billNo, otherType);
        flowingWaterExpandMapper.insert(flowingWaterEntity);

        return payRecord.getId();
    }

    public ParkingRentPayRecordEntity getNormalById(Integer id) {
        QueryWrapper<ParkingRentPayRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        wrapper.eq("state", ParkingRentPayRecordEntity.STATE_NORMAL);

        return Optional.ofNullable(parkingRentPayRecordMapper.selectOne(wrapper)).orElseThrow(() -> new BusinessException("缴费记录不存在", String.format("id: %s", id)));
    }

    public void delete(Integer id) {
        ParkingRentPayRecordEntity payRecordEntity = new ParkingRentPayRecordEntity();
        payRecordEntity.setId(id);
        payRecordEntity.setState(ParkingRentPayRecordEntity.STATE_DELETED);
        parkingRentPayRecordMapper.updateById(payRecordEntity);
    }

    @Autowired
    public void setParkingRentPayRecordMapper(ParkingRentPayRecordMapper parkingRentPayRecordMapper) {
        this.parkingRentPayRecordMapper = parkingRentPayRecordMapper;
    }

    @Autowired
    public void setWalletService(WalletService walletService) {
        this.walletService = walletService;
    }
}
